<?php


namespace app\model;


use think\facade\Db;
use think\Model;

class Welfare extends Model
{


    /**
     * 列表
     * @param array $map
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list(array $map)
    {
        $where[] = ['status', '=', 1];
        if (!empty($map['type'])) {
            $where[] = ['type', '=', $map['type']];
        }
        if (!empty($map['mechanism_id'])) {
            $where[] = ['mechanism', '=', $map['mechanism_id']];
        }
        $result = $this->field("id,name,mechanism,num,integral,min_integral,max_integral,type,sort,images,details,summary,FROM_UNIXTIME(created_time,'%Y-%m-%d %h:%i:%s') as created_time")
            ->where($where)
            ->order('sort desc')
            ->paginate($map['limit'])
            ->toArray();
        if (!empty($result['data'])) {
            foreach ($result['data'] as &$v) {
                $log = Db::name('welfare_log')
                    ->where(['welfare_id' => $v['id']]);
                $v['count'] = $log->count();//次数
                $total = $log->field('sum(integral) as user_integral')->group('user_id')->select()->toArray();
                $actual_integral = array_sum(array_column($total, 'user_integral'));
                $v['already_integral'] = $actual_integral + $v['integral'];//已筹积分
                $actual_num = count($total);//实际人数
                $v['already_num'] = $actual_num + $v['num'];//实际人数
                unset($v['num']);
                unset($v['integral']);
                $v['echanism'] = Db::name('welfare_echanism')->where(['id' => $v['mechanism']])->find();
            }
        }
        return app('json')->json_success('成功', $result);
    }


    /**
     * 公益进度
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function WelfareSchedule($id)
    {
        $log = Db::name('welfare_article')->where(['w_id' => $id])->select()->toArray();
        return app('json')->json_success('成功', $log);
    }

    /**
     * 详情
     * @param array $map
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function log(array $map)
    {
        $log = Db::name('welfare_log')
            ->withAttr('username', function ($value, $data) {
                return '*' . mb_substr($value, 1);
            })
            ->where(['welfare_id' => $map['welfare_id']])
            ->paginate($map['limit'])
            ->toArray();
        return app('json')->json_success('成功', $log);
    }


    /**
     * 捐赠
     * @param $map
     * @param $model
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function Donate($map, $model)
    {
        $details = $this->where(['id' => $map->data['welfare_id']])->find();
        if (!$details) {
            return app('json')->json_error('公益项目不存在');
        }
        if ($map->data['integral'] <= 0) {
            return app('json')->json_error('捐赠积分不能为0');
        }
        if ($map->data['integral'] < $details['min_integral']) {
            return app('json')->json_error('捐赠积分最低为：' . $details['min_integral']);
        }
        if ($map->user->integral < $map->data['integral']) {
            return app('json')->json_error('积分不足');
        }
        Db::startTrans();
        try {
            $already_user = $model->where(['welfare_id' => $map->data['welfare_id']])->sum('integral');
            $already = $already_user + $details['integral'];
            if (($already + $map->data['integral']) > $details['max_integral']) {
                return app('json')->json_error('捐赠失败，只用捐赠' . ($details['max_integral'] - $already) . '积分就可以了');
            }
            MoneyLog::SetUserMoney($map->user_id, $map->user->integral, $map->data['integral'], 2, 2, '捐赠积分');
            $welfare_log = array(
                'user_id' => $map->user_id,
                'welfare_id' => $map->data['welfare_id'],
                'integral' => $map->data['integral'],
                'username' => $map->user->username,
            );
            $model->save($welfare_log);
            Db::commit();
            return app('json')->json_success('成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return app('json')->json_error('捐赠失败');
        }
    }


    /**
     * 我的公益
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function MyWelfare($data)
    {
        $log = Db::name('welfare_log')
            ->alias('a')
            ->leftJoin('welfare b', 'a.welfare_id = b.id')
            ->field('a.id,a.integral,a.created_time,b.name,b.images')
            ->where(['user_id' => $data['user_id']])
            ->whereTime('a.created_time', 'between', [$data['start_time'], $data['end_time']])
            ->paginate($data['limit'])
            ->toArray();
        $log['totals'] = Db::name('welfare_log')->where(['user_id' => $data['user_id']])
            ->field('count(id) as total_num,sum(integral) as total_integral')
            ->whereTime('created_time', 'between', [$data['start_time'], $data['end_time']])
            ->find();
        return app('json')->json_success('成功', $log);
    }


}